package com.superfish.cutieshop;


import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.sdk.android.AlibabaSDK;
import com.alibaba.sdk.android.callback.InitResultCallback;
import com.lidroid.xutils.DbUtils;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.superfish.cutieshop.file.FStoreLoc;
import com.superfish.cutieshop.file.FileCreateFailureException;
import com.superfish.cutieshop.file.SdCardNotMountedException;
import com.superfish.cutieshop.file.SdCardNotValidException;
import com.superfish.cutieshop.file.Storage;
import com.superfish.cutieshop.http.CallBackStores;
import com.superfish.cutieshop.utils.CommonUtil;
import com.superfish.cutieshop.utils.LogTest;
import com.superfish.cutieshop.utils.MD5Utils;
import com.superfish.cutieshop.utils.Manifest;
import com.superfish.cutieshop.utils.PersistTool;
import com.superfish.cutieshop.utils.ScreenManager;
import com.superfish.cutieshop.utils.UID;
import com.superfish.cutieshop.utils.UserInfo;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;
import java.util.List;

import cn.smssdk.SMSSDK;

public class BaseApp extends Application {

    public static DbUtils mDb;

    /**
     * 数据库的默认名称
     **/
    private static final String DBNAME = "superfish.db";
    // 数据库版本号
    protected static int DBVERSION = 1;

    public static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        initBugly();
        initTaobao();
        SMSSDK.initSDK(this, BaseConfig.SMS_APPKEY, BaseConfig.SMS_APPSECRET);
        PersistTool.init(getApplicationContext());
        initImageLoader();
        initFileStores();
        //初始化数据库
        createDb();
    }

    private void initTaobao() {
        AlibabaSDK.asyncInit(this, new InitResultCallback() {

            @Override
            public void onSuccess() {
                LogTest.lmh("Application-onCreate-initTaobao:onSuccess");
            }

            @Override
            public void onFailure(int code, String message) {
                LogTest.lmh("Application-onCreate-initTaobao:onFailure");
            }

        });
    }

    /**
     * 初始化bugly
     **/
    private void initBugly() {
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(getApplicationContext()); //
        // App的策略Bean
        strategy.setAppChannel(getAppChannel()); //
        // 设置渠道
        try {
            strategy.setAppVersion(CommonUtil
                    .getClientVersionName(getApplicationContext()));
        } catch (Exception e) {
            e.printStackTrace();
        } // App的版本
        strategy.setAppReportDelay(1000); // 设置SDK处理延时，毫秒
        String appId = "900008463"; // 上Bugly(bugly.qq.com)注册产品获取的AppId
        CrashReport.initCrashReport(getApplicationContext(), appId, true); //
    }

    /**
     * 初始化ImageLoader
     */
    private void initImageLoader() {
        /** 初始化ImageLoader 处理图片 --初始化放到这里 可以统一管理下缓存目录 **/
        // 建议给默认地址 如果子类不实现
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                getApplicationContext())
                // .writeDebugLogs()
                // 线程池内加载的数量
                .threadPoolSize(3)
                .memoryCache(new UsingFreqLimitedMemoryCache(4 * 1024 * 1024))
                        // 缓存到内存中的图片
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                        // 缓存的文件数量
                .diskCache(new UnlimitedDiskCache(new File(imageCacheDir())))
                .build();
        ImageLoader.getInstance().init(config);
    }


    /**
     * 初始化文件管理工具
     */
    private void initFileStores() {
        FStoreLoc.BIGFILE.setBaseDirName(getApplicationContext(), BaseConfig.APP_DIR_NAME);
        FStoreLoc.BIGFILE.switchTo(getApplicationContext(), Storage.CARD_EXT);
    }

    /**
     * 创建数据库
     *
     * @return
     */
    public DbUtils createDb() {
        if (mDb == null) {
            mDb = DbUtils.create(getApplicationContext(), DBNAME, DBVERSION, new ZokeDBUpdateListener());
        }
        return mDb;
    }


    /**
     * 获取文件后缀名
     *
     * @return
     * @method
     */
    public static String getFileSuffix(String url) {
        String prefix = url.substring(url.lastIndexOf("."));
        return prefix;
    }

    /**
     * 创建文件名字
     *
     * @param url 网络Url
     * @return
     */
    public static String createFileName(String url) {
        // ----统一命名规则
        try {
            String suffix = getFileSuffix(url);
            return MD5Utils.toMD5(url) + suffix;
        } catch (Exception e) {
            return MD5Utils.toMD5(url);
        }

    }

    /**
     * 数据库版本更新监听
     **/
    public class ZokeDBUpdateListener implements DbUtils.DbUpgradeListener {

        @Override
        public void onUpgrade(DbUtils dbUtils, int oldVersion, int newVersion) {
            try {
                switch (oldVersion) {
                    case 1:
                    case 2:
                    default:
                        break;
                }
            } catch (Exception e) {
            }
        }
    }

    /**
     * 获取设备号
     **/
    public static String getDeviceId() {
        String deviceId = PersistTool.getString(BaseConfig.ShareKey.PHONE_DEVICE, "");
        if (TextUtils.isEmpty(deviceId)) {
            deviceId = MD5Utils.toMD5(CommonUtil.getDeviceId(mContext));
            PersistTool.saveString(BaseConfig.ShareKey.PHONE_DEVICE, deviceId);
        }
        return deviceId;
    }


    /**
     * 获取缓存目录 cache/images/xxxx cache目录要清理缓存
     **/
    public static String getImageCacheDir(Context context) {
        String cacheDir = "";
        try {
            // 所有图片的地址 切换图片的缓存地址 -- 优先使用sd卡
            cacheDir = FStoreLoc.SURVIVE.getImagesCacheDir(context,
                    FStoreLoc.DirLevel.DEFAULT).getPath();
        } catch (SdCardNotMountedException e1) {
            e1.printStackTrace();
        } catch (SdCardNotValidException e1) {
            e1.printStackTrace();
        } catch (FileCreateFailureException e1) {
            e1.printStackTrace();
        }
        return cacheDir;
    }


    /**
     * 获取临时文件 -- 类似于裁减头像 临时压缩处理的路径 /cache/temp/xxxx
     **/
    public static String getTempCache(Context context) {
        String cacheDir = "";
        try {
            // 所有图片的地址 切换图片的缓存地址 -- 优先使用sd卡
            cacheDir = FStoreLoc.SURVIVE.getTempCacheDir(context,
                    FStoreLoc.DirLevel.DEFAULT).getPath();
        } catch (SdCardNotMountedException e1) {
            e1.printStackTrace();
        } catch (SdCardNotValidException e1) {
            e1.printStackTrace();
        } catch (FileCreateFailureException e1) {
            e1.printStackTrace();
        }
        return cacheDir;
    }

    /**
     * 获取缓存目录 cache/xxxx cache目录要清理缓存
     **/
    public static String getCacheDir(Context context) {
        String cacheDir = "";
        try {
            // 所有图片的地址 切换图片的缓存地址 -- 优先使用sd卡
            cacheDir = FStoreLoc.SURVIVE.getCacheDir(context, FStoreLoc.DirLevel.DEFAULT)
                    .getPath();
        } catch (SdCardNotMountedException e1) {
            e1.printStackTrace();
        } catch (SdCardNotValidException e1) {
            e1.printStackTrace();
        } catch (FileCreateFailureException e1) {
            e1.printStackTrace();
        }
        return cacheDir;
    }

    /**
     * 直接用友盟的channel
     **/
    public static String getAppChannel() {
        return Manifest.MetaData.getString(mContext, "UMENG_CHANNEL");
    }


    public static String getNextUidToken() {
        return UID.nextToken(mContext);
    }


    /**
     * 图片缓存文件路径
     **/
    protected String imageCacheDir() {
        //
        return getImageCacheDir(getApplicationContext());
    }

    /**
     * 执行双击退出app
     **/
    public void exitApp() {
        CallBackStores.getCallback().clearCallbacks();
        ScreenManager.getScreenManager().popAllActivityExceptOne();
    }


    /**
     * 是否登录
     **/
    public static boolean isLogin() {
        String token = UserInfo.getInstense(mContext).getToken();
        return !TextUtils.isEmpty(token);
    }

    /**
     * 是否是游客登录
     **/
    public static boolean isGuest() {
        boolean isLogin = PersistTool.getBoolean(BaseConfig.ShareKey.ISLOGIN, false);
        return !isLogin;
    }


    /**
     * 评论应用 requestCode=0
     **/
    public static void openAppMarketsAtMyDetails(Activity activity,
                                                 int requestCode) {
        String uri = "market://details?id=" + mContext.getPackageName();
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(uri));
        // 如果没有安装任何应用市场，则startActivity()会报错
        // PackageManager.MATCH_DEFAULT_ONLY用于非Launcher但是可以接受data的Intent.CATEGORY_DEFAULT
        List<ResolveInfo> infos = mContext.getPackageManager()
                .queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY);
        if (infos != null && infos.size() > 0) {
            // i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // //加这句的话，App还没启动，就会收到onActivityResult()
            try {
                activity.startActivity(i);
            } catch (Exception e) {

            }
        }
    }

    public static void test() {
        LogTest.lmh("Application-test:进入");
        PersistTool.saveBoolean(BaseConfig.ShareKey.HAS_NEW_NOTIFY, true);
    }
}
